// 路由守卫
// 加载进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//引入路由Router的js文件
import router from '@/router'
import { RouteLocationNormalized } from 'vue-router'
//引入store的index.js文件和UserActionTypes的js文件
import { useStore } from './store'
import { UserActionTypes } from './store/modules/user/action-types'
//引入信息组件
import { message } from 'ant-design-vue';

const whiteList: string[] = ["/passport/login"]; // 路由白名单

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: any) => {
  // Start progress bar
  NProgress.start()
  const store = useStore()
  // Determine whether the user has logged in
  if (useStore().state.user.token) {
    if (to.path === '/passport/login') {
      // If is logged in, redirect to the home page
      next({ path: '/' })
      // NProgress.done()
    } else {
      // Check whether the user has obtained his permission roles
      if (store.state.user.roles.length === 0) {
        store.dispatch(UserActionTypes.ACTION_RESET_TOKEN, undefined)
        next(`/login?redirect=${to.path}`)
        // NProgress.done()
      } else {
        // if(s)
        if (to.meta.permission) {
          // 菜单需要权限才可以进入
          if (store.state.user.permissions.includes(to.meta.permission as any)) {
            next();
          } else {
            next({ path: '/404' })
          }
        } else {
          next()
        }
        // NProgress.done()
      }
    }
  } else {
    // Has no token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      next()
    } else {
      // Other pages that do not have permission to access are redirected to the login page.
      next(`/passport/login?redirect=${to.path}`)
      // NProgress.done()
    }
  }
})

router.afterEach((to: RouteLocationNormalized) => {
  // Finish progress bar
  // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  NProgress.done()
  // set page title
  // document.title = getPageTitle(to.meta.title)
})
